# coding:utf-8
from scrapyExercise import settings
import redis, random, threading

class RedisUtil(object):
    _instance_lock = threading.Lock()

    def __init__(self):
        pass

    def __new__(cls, *args, **kwargs):
        if not hasattr(RedisUtil, "_instance"):
            with RedisUtil._instance_lock:
                if not hasattr(RedisUtil, "_instance"):
                    pool = redis.ConnectionPool(host=settings.REDIS_HOST, port=settings.REDIS_PORT,
                                                db=settings.REDIS_DB, password=settings.REDIS_PWD)
                    RedisUtil._redis_conn = redis.Redis(connection_pool=pool)
                    RedisUtil._instance = object.__new__(cls)
        return RedisUtil._instance

    def lindex(self, redis_table, index='random'):
        if index=='random':
            length = self._redis_conn.llen(redis_table)
            index = random.randint(0, length-1)
        result = self._redis_conn.lindex(redis_table, index)
        return str(result.decode())

    def srandmember(self, redis_table, count):
        result = self._redis_conn.srandmember(redis_table, count)
        return str(result[0].decode())

    def setnx(self, key, value):
        return self._redis_conn.setnx(key, value)

    def expire(self, key, value):
        return self._redis_conn.expire(key, value)

    def hget(self, key, value):
        return self._redis_conn.hget(key, value)

    def hset(self, redis_table, house_id, info):
        return self._redis_conn.hset(redis_table, house_id, info)

    def exists(self, key):
        return self._redis_conn.exists(key)

    def sadd(self, redis_table, info):
        self._redis_conn.sadd(redis_table, info)

    def disconnect(self):
        self._redis_conn.connection_pool.disconnect()
